"use client"

import { useState, useEffect } from "react"
import { useParams, useRouter } from "next/navigation"
import { motion } from "framer-motion"
import { 
  MapPin, 
  Calendar, 
  Github, 
  Linkedin, 
  Globe,
  Mail,
  ChevronLeft,
  TrendingUp
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { usersApi, User } from "@/lib/api"
import { useAuth } from "@/contexts/auth-context"
import { LoadingScreen } from "@/components/loading-screen"

export default function UserDetailPage() {
  const params = useParams()
  const router = useRouter()
  const { user: currentUser, isAuthenticated } = useAuth()
  const [user, setUser] = useState<User | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isFollowing, setIsFollowing] = useState(false)

  useEffect(() => {
    const fetchUser = async () => {
      try {
        setIsLoading(true)
        const response = await usersApi.getUser(Number(params.id))
        setUser(response)
      } catch (error) {
        console.error("Failed to fetch user:", error)
        router.push("/")
      } finally {
        setIsLoading(false)
      }
    }

    if (params.id) {
      fetchUser()
    }
  }, [params.id, router])

  const handleFollow = async () => {
    if (!isAuthenticated) {
      router.push("/auth/login")
      return
    }
    
    try {
      // TODO: 实现关注/取消关注的API调用
      setIsFollowing(!isFollowing)
    } catch (error) {
      console.error("Failed to toggle follow:", error)
    }
  }

  const handleMessage = () => {
    if (!isAuthenticated) {
      router.push("/auth/login")
      return
    }
    // TODO: 实现私信功能
    console.log("Send message to user")
  }

  if (isLoading) {
    return <LoadingScreen />
  }

  if (!user) {
    return (
      <div className="min-h-screen pt-20 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-white mb-4">用户不存在</h1>
          <Button onClick={() => router.push("/")} variant="outline">
            返回首页
          </Button>
        </div>
      </div>
    )
  }

  const isOwnProfile = currentUser?.id === user.id

  return (
    <div className="min-h-screen pt-20">
      <div className="container mx-auto px-4 py-8">
        {/* 返回按钮 */}
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          className="mb-6"
        >
          <Button
            variant="ghost"
            onClick={() => router.back()}
            className="text-white hover:text-blue-300"
          >
            <ChevronLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
        </motion.div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 用户信息卡片 */}
          <div className="lg:col-span-1">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="space-y-6"
            >
              <Card className="bg-gray-800/50 border-gray-700">
                <CardContent className="p-6">
                  <div className="text-center mb-6">
                    <Avatar className="w-24 h-24 mx-auto mb-4">
                      <AvatarImage src={user.avatar_url || ""} alt={user.username} />
                      <AvatarFallback className="text-2xl bg-gradient-to-r from-blue-500 to-purple-500">
                        {user.username.charAt(0).toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                    <h1 className="text-2xl font-bold text-white mb-2">
                      {user.full_name || user.username}
                    </h1>
                    <p className="text-gray-400 mb-2">@{user.username}</p>
                    {user.bio && (
                      <p className="text-gray-300 text-sm">{user.bio}</p>
                    )}
                  </div>

                  {/* 操作按钮 */}
                  {!isOwnProfile && (
                    <div className="flex gap-2 mb-6">
                      <Button
                        onClick={handleFollow}
                        className="flex-1 bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
                      >
                        {isFollowing ? "已关注" : "关注"}
                      </Button>
                      <Button
                        variant="outline"
                        onClick={handleMessage}
                        className="border-gray-600 text-white hover:bg-gray-700"
                      >
                        私信
                      </Button>
                    </div>
                  )}

                  {/* 基本信息 */}
                  <div className="space-y-3">
                    {user.location && (
                      <div className="flex items-center gap-2 text-gray-300">
                        <MapPin className="w-4 h-4" />
                        <span>{user.location}</span>
                      </div>
                    )}
                    <div className="flex items-center gap-2 text-gray-300">
                      <Calendar className="w-4 h-4" />
                      <span>加入于 {new Date(user.created_at).toLocaleDateString("zh-CN")}</span>
                    </div>
                    {user.email && (
                      <div className="flex items-center gap-2 text-gray-300">
                        <Mail className="w-4 h-4" />
                        <span>{user.email}</span>
                      </div>
                    )}
                  </div>

                  {/* 社交链接 */}
                  {(user.github_url || user.linkedin_url || user.website_url) && (
                    <div className="mt-6 pt-6 border-t border-gray-700">
                      <h3 className="text-white font-semibold mb-3">社交链接</h3>
                      <div className="space-y-2">
                        {user.github_url && (
                          <a
                            href={user.github_url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center gap-2 text-gray-300 hover:text-white transition-colors"
                          >
                            <Github className="w-4 h-4" />
                            <span>GitHub</span>
                          </a>
                        )}
                        {user.linkedin_url && (
                          <a
                            href={user.linkedin_url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center gap-2 text-gray-300 hover:text-white transition-colors"
                          >
                            <Linkedin className="w-4 h-4" />
                            <span>LinkedIn</span>
                          </a>
                        )}
                        {user.website_url && (
                          <a
                            href={user.website_url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center gap-2 text-gray-300 hover:text-white transition-colors"
                          >
                            <Globe className="w-4 h-4" />
                            <span>个人网站</span>
                          </a>
                        )}
                      </div>
                    </div>
                  )}

                  {/* 技能标签 */}
                  {user.skills && user.skills.length > 0 && (
                    <div className="mt-6 pt-6 border-t border-gray-700">
                      <h3 className="text-white font-semibold mb-3">技能</h3>
                      <div className="flex flex-wrap gap-2">
                        {user.skills.map((skill) => (
                          <Badge key={skill} variant="secondary" className="bg-blue-500/20 text-blue-300">
                            {skill}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* 统计数据 */}
              <Card className="bg-gray-800/50 border-gray-700">
                <CardHeader>
                  <CardTitle className="text-white flex items-center gap-2">
                    <TrendingUp className="w-5 h-5 text-green-400" />
                    统计数据
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex justify-between items-center">
                    <span className="text-gray-300">声誉分</span>
                    <span className="text-xl font-bold text-yellow-400">{user.reputation || 0}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-300">参与竞赛</span>
                    <span className="text-white">0</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-300">创建项目</span>
                    <span className="text-white">0</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-300">加入团队</span>
                    <span className="text-white">0</span>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </div>

          {/* 主要内容区域 */}
          <div className="lg:col-span-2">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2 }}
            >
              <Tabs defaultValue="activity" className="w-full">
                <TabsList className="grid w-full grid-cols-4 bg-gray-800/50">
                  <TabsTrigger value="activity" className="text-white">动态</TabsTrigger>
                  <TabsTrigger value="competitions" className="text-white">竞赛</TabsTrigger>
                  <TabsTrigger value="projects" className="text-white">项目</TabsTrigger>
                  <TabsTrigger value="achievements" className="text-white">成就</TabsTrigger>
                </TabsList>

                <TabsContent value="activity" className="mt-6">
                  <Card className="bg-gray-800/50 border-gray-700">
                    <CardHeader>
                      <CardTitle className="text-white">最近动态</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="text-center py-12">
                        <div className="text-6xl mb-4">📝</div>
                        <h3 className="text-xl font-semibold text-white mb-2">暂无动态</h3>
                        <p className="text-gray-300">该用户还没有发布任何动态</p>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent value="competitions" className="mt-6">
                  <Card className="bg-gray-800/50 border-gray-700">
                    <CardHeader>
                      <CardTitle className="text-white">参与的竞赛</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="text-center py-12">
                        <div className="text-6xl mb-4">🏆</div>
                        <h3 className="text-xl font-semibold text-white mb-2">暂无竞赛记录</h3>
                        <p className="text-gray-300">该用户还没有参与任何竞赛</p>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent value="projects" className="mt-6">
                  <Card className="bg-gray-800/50 border-gray-700">
                    <CardHeader>
                      <CardTitle className="text-white">创建的项目</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="text-center py-12">
                        <div className="text-6xl mb-4">💻</div>
                        <h3 className="text-xl font-semibold text-white mb-2">暂无项目</h3>
                        <p className="text-gray-300">该用户还没有创建任何项目</p>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent value="achievements" className="mt-6">
                  <Card className="bg-gray-800/50 border-gray-700">
                    <CardHeader>
                      <CardTitle className="text-white">成就徽章</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="text-center py-12">
                        <div className="text-6xl mb-4">🏅</div>
                        <h3 className="text-xl font-semibold text-white mb-2">暂无成就</h3>
                        <p className="text-gray-300">该用户还没有获得任何成就徽章</p>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>
              </Tabs>
            </motion.div>
          </div>
        </div>
      </div>
    </div>
  )
}